//
//  LoginViewController.m
//  healthApp
//
//  Created by william mu on 12-8-28.
//  Copyright (c) 2012年 Tencent. All rights reserved.
//

#import "LoginViewController.h"
#import "RootController.h"
#import "MainEntryController.h"
#import "ProtocolService.h"
#import "BottomBarController.h"
#import "Common.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize loginBtn;
@synthesize resetBtn;
@synthesize userNameTxt;
@synthesize passwordTxt;
@synthesize changeSvrBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    m_allRequest = [[NSMutableArray array] retain];
    [self initChangeSvrBtn];
}

-(void) initChangeSvrBtn
{
    [self.changeSvrBtn addTarget:self action:@selector(onServerChangeBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    NSString* svrBase = [defaults stringForKey:SVR_BASE_KEY];
    
    if(!svrBase){
        svrBase = @"http://localhost/healthProj";
        [defaults setObject:svrBase forKey:SVR_BASE_KEY];
    }
    
    [self.changeSvrBtn setTitle:svrBase forState:UIControlStateNormal];
}

-(void) onServerChangeBtn:(UIButton*) svrChangeBtn
{
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Who are you?"     
                                                    message:@"Please enter server path:" 
                                                   delegate:self  cancelButtonTitle:@"Cancel"   
                                          otherButtonTitles:@"OK", nil]; 
    [alert addTextFieldWithValue:@"" label:@"ServerBase:"]; 
    
    UITextField* svrAddrTxt = [alert textFieldAtIndex:0];
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    NSString* svrBase = [defaults stringForKey:SVR_BASE_KEY];
    svrAddrTxt.text = svrBase;
    
    
    [alert show];
    
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex != 1)
        return;
    
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    UITextField* svrAddrTxt = [alertView textFieldAtIndex:0]; 
    NSString* svrAddr = [svrAddrTxt text];
    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:svrAddr forKey:SVR_BASE_KEY];
    
    [self.changeSvrBtn setTitle:svrAddr forState:UIControlStateNormal];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.loginBtn = nil;
    self.resetBtn = nil;
    self.userNameTxt = nil;
    self.passwordTxt = nil;
    self.changeSvrBtn = nil;
    [m_allRequest release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) onLogin:(id) sender
{
    
    ProtocolService* protocol = [ProtocolService sharedInstance];
    [protocol shutdownAnyResponse:m_allRequest];
    [m_allRequest removeAllObjects];
    
    NSString* username = self.userNameTxt.text;
    NSString* password = self.passwordTxt.text;
    
    [protocol setTarget:self];
    [protocol setAction:@selector(onLoginResponse:)];
    NSString* seq = [protocol loginWithUserName:username password:password];
    [m_allRequest addObject:seq];
    
}

-(void) reset:(id) sender
{
    self.userNameTxt.text = @"";
    self.passwordTxt.text = @"";
}

-(void) onLoginFailure
{
    NSLog(@"login failure!");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败" message:@"用户名/密码错误！" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];  
    
    [alert show];  
    [alert release];  
}

-(void) onGetUid:(NSString*) json
{
    GlobalState* state = [GlobalState sharedInstance];
    state.uid = json;
    
    ProtocolService* protocol = [ProtocolService sharedInstance];
    
    [protocol setTarget:self];
    [protocol setAction:@selector(onGetSymptomMap:)];
    NSString* seq = [protocol getSymptomMap];
    [m_allRequest addObject:seq];
}

-(void) onGetSymptomMap:(NSString*) json
{
    NSArray* ary = (NSArray*)[json JSONValue];
    GlobalState* state = [GlobalState sharedInstance];
    
    state.symptomMap = [[NSMutableDictionary dictionary] retain];
    
    for(int i = 0; i < [ary count]; i++)
    {
        NSString* code = [NSString stringWithFormat:@"%d", i];
        
        NSString* desc = [ary objectAtIndex:i];
        
        [state.symptomMap setObject:desc forKey:code];
    }
    
    ProtocolService* protocol = [ProtocolService sharedInstance];
    
    [protocol setTarget:self];
    [protocol setAction:@selector(onGetHealthFieldMap:)];
    NSString* seq = [protocol getHealthFieldMap];
    [m_allRequest addObject:seq];
}

-(void) onGetHealthFieldMap:(NSString*) json
{
    GlobalState* state = [GlobalState sharedInstance];
    state.healthFieldMap = (NSDictionary*)[json JSONValue];
    [self startMainView];
}

-(void) startMainView
{
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    
    RootController* rootController = [RootController sharedInstance];
    
    MainEntryController* mainEntryController = [[MainEntryController alloc] init];
    
    [center addObserver:mainEntryController selector:@selector(onBottomBarTap:) name:BOTTOM_BAR_TAP object:nil];
    
    rootController.navController = [[[UINavigationController alloc] initWithRootViewController:mainEntryController] autorelease];
    
    [mainEntryController release];
    
    [rootController loadController:rootController.navController];
    BottomBarController* bottomBarController = [[BottomBarController alloc] init];
    [rootController loadController:bottomBarController];
    rootController.wantsFullScreenLayout = YES;
    rootController.bottomBarController = bottomBarController;
    [bottomBarController release];
    
    rootController.navController.view.frame=CGRectMake(0.0, 0.0, 320, 480 - bottomBarController.view.bounds.size.height);
    
    [rootController unloadController:self];
}

-(void) onLoginSuccess
{
    ProtocolService* protocol = [ProtocolService sharedInstance];
    
    [protocol setAction:@selector(onGetUid:)];
    [protocol setTarget:self];
    NSString* seq = [protocol requestMyUid];
    [m_allRequest addObject:seq];
}

-(void) onLoginResponse:(NSString*) json
{
    if([json isEqualToString:@"success"])
    {
        [self onLoginSuccess];
    }else {
        [self onLoginFailure];
    }
    

}

@end
